package io.aircraft.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.aircraft.common.constant.SerialNumConstants;
import io.aircraft.common.service.impl.CrudServiceImpl;
import io.aircraft.common.utils.DateUtils;
import io.aircraft.modules.wms.dao.SerialNumberDao;
import io.aircraft.modules.wms.dto.SerialNumberDTO;
import io.aircraft.modules.wms.entity.SerialNumberEntity;
import io.aircraft.modules.wms.service.SerialNumberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 流水号信息
 *
 * @author Cycle gengruyi01@163.com
 * @since 1.0.0 2022-10-27
 */
@Service
public class SerialNumberServiceImpl extends CrudServiceImpl<SerialNumberDao, SerialNumberEntity, SerialNumberDTO> implements SerialNumberService {
    /**
     * 格式
     */
    private String pattern = "";
    /**
     * 最小值
     */
    private long minSeed = 1;
    /**
     * 种子
     */
    private long seed = 0;
    /**
     * 数据库存储的当前序列号
     */
    String maxSerial = "";
    /**
     * 当前序列号是否为个位数自增的模式
     */
    private String isAutoIncrement = "0";

    @Override
    public QueryWrapper<SerialNumberEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<SerialNumberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public String getSerialNumberByCode(String code) {
        SerialNumberEntity entity = getByCode(code);
        String formatSerialNum = entity.getConfigTemplate();
        maxSerial = entity.getMaxSerial();
        pattern = entity.getConfigTemplate();
        //动态序号拼接
        for (int i = 0; i < maxSerial.length(); i++) {
            formatSerialNum = StringUtils.removeEnd(formatSerialNum, "0");
        }
        formatSerialNum = StringUtils.join(formatSerialNum, maxSerial);
        //动态日期生成
        if (pattern.contains(SerialNumConstants.DATE_SYMBOL)) {
            String currentDate = DateUtils.format(new Date(), "yyyyMMdd");
            formatSerialNum = formatSerialNum.replace(SerialNumConstants.DATE_SYMBOL, currentDate);
        }
        //校验序号是否过大(长度超过6位重新计数)
        if (maxSerial.length() > 6) {
            seed = minSeed;
        } else {
            seed = Long.parseLong(maxSerial) + 1;
        }
        //将新的序列号写入数据库
        entity.setMaxSerial(String.valueOf(seed));
        this.updateById(entity);
        return formatSerialNum;
    }

    @Override
    public SerialNumberEntity getByCode(String code) {
        return baseDao.selectOne(new QueryWrapper<SerialNumberEntity>().eq("module_code", code));
    }
}